package com.gwlc.common.base;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>lucky-com.gwlc.common.base-BaseAop</p>
 * <p>Description:  切面基类</p>
 * <p>Copyright: Copyright (c) 2021</p>
 * <p>Company: hanchunit@163.com</p>
 *
 * @author hanchun
 * @version 1.0
 * @date 2021/9/20
 */
public class BaseAop {

    private String token = null;

    /**
     * 获取Header中的token
     * 如果Header中没有则在Cookie中获取
     *
     * @return 获取到的token
     */
    public String getToken() {
        HttpServletRequest request = getRequest();
        token = getHeaderToken(request);
        if (token == null) {
            token = getCookieToken(request);
        }
        return token;
    }

    /**
     * 获取Request请求
     */
    public HttpServletRequest getRequest() {

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        return sra.getRequest();
    }

    /**
     * 获取Header中的token
     * 如果Header中没有则在Cookie中获取
     *
     * @return 获取到的token
     */
    public String getHeaderToken(HttpServletRequest request) {

        token = request.getHeader("token");


        return token;
    }

    /**
     * 获取cookie中的token
     *
     * @param request 请求
     * @return 结果
     */
    public String getCookieToken(HttpServletRequest request) {
        //获取本地的cookies

        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
        }
        return token;

    }

    /**
     * 验证超时时间
     *
     * @param outTime 超时时间
     * @return 是否超时
     */
    public boolean verifyOutTime(Long outTime) {

        return outTime == null || outTime < System.currentTimeMillis();
    }
}
